﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;

using MiniSched.Orm;
using MiniSched.Web.Areas.Api.Controllers;
using MiniSched.Web.Models.Account;

namespace MiniSched.Web.Controllers {

    public class AccountController : BaseController<AccountApiController> {

        [HttpGet]
        [AllowAnonymous]
        public ActionResult Register() {
            return View(new RegisterModel());
        }

        [HttpPost]
        [AllowAnonymous]
        [ValidateAntiForgeryToken]
        public ActionResult Register(RegisterModel model) {            

            var userName = model.UserName;
            var password = model.Password;

            try {
                Api.WebSecurity.CreateUserAndAccount(userName, password);
            }
            catch (MembershipCreateUserException) {
                throw;
            }
            Api.WebSecurity.Login(userName, password);
            return RedirectToAction("Index", "Home");
        }

        [HttpGet]
        [AllowAnonymous]
        public ActionResult Login(string returnUrl) {
            return View(new LoginModel { ReturnUrl = returnUrl });
        }

        [HttpPost]
        [AllowAnonymous]
        [ValidateAntiForgeryToken]
        public ActionResult Login(LoginModel model) {

            if (Api.WebSecurity.Login(model.UserName, model.Password, model.PersistCookie)) {
                return RedirectToLocal(model.ReturnUrl);
            }
            return View(model);
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Logout() {
            Api.WebSecurity.Logout();
            return RedirectToAction("Index", "Home");
        }
    }
}
